﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LingDong.ConfigProvider;
using System.IO;

namespace LingDong.IndexCreator.Helper
{
    internal class SubIndexNameHelper
    {
        #region Internal Methods

        internal SubIndexNameHelper()
        {
            subIndexDir = ConfigCommon.Default.LingDongDataRoot + ConfigIndex.Default.SubIndexDir;
            Directory.CreateDirectory(subIndexDir);

            // find next prefix number can be used
            currentPrefixNumber = 0;
            while (AnyIndexFileExists())
            {
                currentPrefixNumber++;
            }
        }

        internal string GetDictionaryFileName()
        {
            return FormatSubIndexFileName(ConfigIndex.Default.DictionaryPostfix);
        }

        internal string GetInvertedListFileName()
        {
            return FormatSubIndexFileName(ConfigIndex.Default.InvertedListPostfix);
        }

        internal string GetDocumentIndexFileName()
        {
            return FormatSubIndexFileName(ConfigIndex.Default.DocumentIndexPostfix);
        }

        internal string GetParsedDocumentFileName()
        {
            return FormatSubIndexFileName(ConfigIndex.Default.ParsedDocumentPostfix);
        }

        internal string GetOriginalDocumentFileName()
        {
            return FormatSubIndexFileName(ConfigIndex.Default.OriginalDocumentPostfix);
        }

        #endregion


        #region Private Methods

        private string FormatSubIndexFileName(string postfix)
        {
            return String.Format("{0}{1}.{2}", subIndexDir, currentPrefixNumber, postfix);
        }

        /// <summary>
        /// Return true only if any one of index filles exists
        /// </summary>
        /// <returns></returns>
        private bool AnyIndexFileExists()
        {
            string[] files = new string[] { 
                GetDictionaryFileName(), 
                GetInvertedListFileName(),
                GetDocumentIndexFileName(), 
                GetParsedDocumentFileName(), 
                GetOriginalDocumentFileName() };
            foreach (string file in files)
            {
                if (File.Exists(file))
                    return true;
            }
            return false;
        }

        #endregion
        

        #region Private Members

        private int currentPrefixNumber;

        private string subIndexDir;
        
        #endregion
    }
}
